extends Area2D

@onready var sprite = $Weapon
@onready var ani:AnimationPlayer = $Weapon/AnimationPlayer

var roting = false
var rot_speed:float = 10
var send_cha_b:bool = false
var copy_pa:Weapon
var dir:Vector2  
var back:bool = false
var v_delta:float =0.0
var fix:float =0.0
var walk_lengh = 1000
var wl = 0.0
var t = 0.0
var times:float = 0
@export var speed:float = 200
func _ready() -> void:
	fix = 0.0
	await get_tree().process_frame
	dir = ($Weapon/DIR.global_position-self.global_position).normalized()


func _process(delta: float) -> void:
	times+=delta
	if !back:
		self.global_position+=dir*speed*delta
		wl+=(dir*speed*delta).length()
		if wl>walk_lengh:
			come_back()
	else:
		v_delta+=delta
		self.sprite.rotation_degrees+=999*delta
		var s = v_delta
		if s>=3.0:
			s=3.0
		self.global_position = lerp(self.global_position,copy_pa.global_position,s)
		if (self.global_position-copy_pa.global_position).length()<5:
			rrrr()

func rrrr():
	set_process(false)
	queue_free()
	copy_pa.reset()

func come_back():
	back = true


func _on_body_entered(body: Node2D) -> void:
	if back:
		return
	if body is StaticBody2D:
		come_back()
		return
	elif body is Player && times > 0.3:
		rrrr()
		return
	elif is_instance_valid(body) && body is Monster &&body.is_alive:
		$Weapon/AnimationPlayer.play("attack")
		body.die()
		come_back()

func _on_area_entered(area: Area2D) -> void:
	if back:
		return
	if is_instance_valid(area) :
		var papa = area.get_parent().get_parent()
		if papa is Gem && papa.state == Gem.STATE.BUBBLIZE:
			$Weapon/AnimationPlayer.play("attack")
			papa.queue_free()
			come_back()
